
package cn.zebra.dev.common.filter;

import cn.zebra.dev.common.utils.StrUtils;

/**
 * SQL过滤
 *
 * @author runnable@sina.cn
 */
public class SqlFilter {

    /**
     * SQL注入过滤
     *
     * @param str 待验证的字符串
     */
    public static String sqlInject(String str) {
        if (StrUtils.isBlank(str)) {
            return null;
        }
        //去掉'|"|;|\字符
        str = str.replace("'", "");
        str = str.replace("\"", "");
        str = str.replace(";", "");
        str = str.replace("\\", "");

        //转换成小写
        str = str.toLowerCase();

        //非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"};

        //判断是否包含非法字符
        for (int i = keywords.length - 1; i >= 0; i--) {
            String keyword = keywords[i];
            if (str.contains(keyword)) {
                throw new RuntimeException("包含非法字符!");
            }
        }
        return str;
    }
}
